<template>
  <div class="container" style="display: flex;justify-content: center">
    <div style="display: flex;width: 1400px">
      <el-aside width="300px">
        <div style="margin-left: 50px">
          <div style="margin-top: 50px">
            <el-avatar shape="square" :size="200"
                       src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png"/>
          </div>
          <div style="margin-top: 50px">
            <el-descriptions
                :column="1"
                :size="2"
                direction="vertical"
                :style="blockMargin"
            >
              <el-descriptions-item align="left" label="Username">
                {{ info.userName }}
              </el-descriptions-item>
              <el-descriptions-item align="left" label="Description">
                <div v-if="myHomePage==true" style="display: block">
                  <div class="editor">
                    <div style="border: 1px solid #ccc; margin-top: 10px">
                      <Editor
                          :defaultConfig="editorConfig"
                          :mode="mode"
                          v-model="valueHtml"
                          style="height: 200px;width: 240px; overflow-y: hidden"
                          @onCreated="handleCreated"
                      ></Editor>
                    </div>
                  </div>
                  <div  style="padding: 20px;display: flex;justify-content: center">
                    <el-button @click="changeUserDescription" type="primary" plain>修改</el-button>
                  </div>
                </div>
                <div v-else>
                  <div  v-html="info.description" class="content" style="width: 300px"> </div>
                </div>
              </el-descriptions-item>
            </el-descriptions>
          </div>
        </div>
      </el-aside>
      <el-main>
        <el-tabs v-model="activeName" class="tabs">
          <el-tab-pane label="仓库" name="Repo">
            <div class="navbar-wrapper">
              <div class="header-container">
                <div class="searchBox">
                  <el-input class="searchBar" v-model="searchName" placeholder="搜索我的仓库" :prefix-icon="Search" >
                    <template #append>
                      <el-button @click="localSearch"  :icon="Search" />
                    </template>
                  </el-input>
                </div>
                <el-link v-if="myHomePage" class="link-item link is-menu-link " @click="newRepo">
                  <el-icon><Edit/></el-icon>
                  新建仓库
                </el-link>
              </div>
            </div>
            <div>
              <el-scrollbar class="scrollbar" max-height="500px">
                <el-table :data="TableData" style="width: 100%">
                  <el-table-column  prop="repoName" label="仓库名"></el-table-column>
                  <el-table-column>
                    <template #default="scope">
                      <el-icon v-if="scope.row.isPrivate===false" ><Unlock></Unlock></el-icon>
                      <el-icon v-if="scope.row.isPrivate===true" ><Lock></Lock></el-icon>
                    </template>
                  </el-table-column>
                  <el-table-column align="right">
                    <template #default="scope">
                      <el-button v-if="myHomePage||scope.row.isPrivate===false" size="small" type="success" @click="IntoRepo(scope.row.repoName)">进入仓库</el-button>
                      <el-button v-if="myHomePage" size="small" type="danger" @click="delRepo(scope.row.repoName)">删除仓库</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-scrollbar>
            </div>
          </el-tab-pane>
          <el-tab-pane v-if="myHomePage" label="通知">
            <div style="display: block">
              <div style="height: 500px">
                <el-scrollbar class="scrollbar" max-height="500px">
                  <div v-for="item in  notifyData" style="display: block;padding: 10px">
                    <div style="display: flex;align-items: center;justify-content:space-between;padding: 10px;border-bottom: 2px solid #e7e7e7">
                      <div style="display: block">
                        <div style="display: flex; padding-bottom: 10px">
                          <el-icon v-if="item.status===false" color="grey"><Bell /></el-icon>
                          <el-icon v-else color="red"><Bell /></el-icon>
                          <div style="padding-left: 10px">
                            {{item.title}}
                          </div>
                        </div>
                        <div style="margin-left: 20px">{{item.content}}</div>
                      </div>
                      <div style="display: block; justify-self: flex-end">
                        <div  style="padding: 5px;height: 30px;width: 50px; display: flex;align-content: center;justify-content: center">
                          <el-button v-if="item.status===true" type="primary" link @click="markRead(item.messageId)">标记为已读</el-button>
                        </div>
                        <div style="padding: 5px;height: 30px;width: 50px;display: flex;align-content: center;justify-content: center">
                          <el-button type="danger" link @click="deleteMessage(item.messageId)">删除信息</el-button>
                        </div>
                      </div>
                    </div>
                  </div>
                </el-scrollbar>
              </div>
              <div style="padding-top:5px ;margin: 10px 0;display: flex;justify-content: center; ">
                <div style="width: 800px;height: 100px">
                  <el-pagination
                      v-model:currentPage="currentPage"
                      :page-sizes="[5, 10, 20, 30]"
                      :page-size="pageSize"
                      layout="total, sizes, prev, pager, next, jumper"
                      :total="total"
                      @size-change="handleSizeChange"
                      @current-change="handleCurrentChange"
                  />
                </div>
                <div><el-button type="primary" @click="markAll">标记为已读</el-button></div>
              </div>
            </div>

          </el-tab-pane>
          <el-tab-pane v-if="myHomePage" label="个人信息管理" name="Info">
            <el-scrollbar class="scrollbar" max-height="500px">
              <div style="grid-column: 2/span 2; display: grid; padding: 05px;width: 90%">
                <div class="titleHead">
                  <h2 class="titleHead-Heading" style="display: flex">
                    <div style="margin-top: 5px">
                      <el-icon>
                        <User/>
                      </el-icon>
                    </div>
                    更改用户名
                  </h2>
                </div>
                <div style="justify-content: flex-start; display: grid;">
                  <div>
                    <p>
                      更改该账户用户名。
                    </p>
                  </div>
                  <el-button @click="changeUserNameVisible = true">更改用户名</el-button>
                  <el-dialog v-model="changeUserNameVisible" title="更改用户名">
                    <el-form :model="form">
                      <el-form-item label="新用户名" :label-width="formLabelWidth">
                        <el-input v-model="form.userName" autocomplete="off"/>
                      </el-form-item>
                    </el-form>
                    <el-button type="primary" @click="changeUserName">
                      确认
                    </el-button>
                  </el-dialog>
                </div>

                <div class="titleHead">
                  <h2 class="titleHead-Heading" style="display: flex">
                    <div style="margin-top: 5px">
                      <el-icon>
                        <Message/>
                      </el-icon>
                    </div>
                    更改邮箱
                  </h2>
                </div>
                <div style="justify-content: flex-start; display: grid;">
                  <div>
                    <p>
                      更改与该账户关联的邮箱。
                    </p>
                  </div>
                  <el-button @click="changeEmailVisible = true">更改邮箱</el-button>
                  <el-dialog v-model="changeEmailVisible" title="更改邮箱">
                    <el-form :model="form">
                      <el-form-item label="新邮箱" :label-width="formLabelWidth">
                        <el-input v-model="form.userEmail" autocomplete="off"/>
                      </el-form-item>
                    </el-form>
                    <el-button type="primary" @click="changeEmail">
                      确认
                    </el-button>
                  </el-dialog>
                </div>

                <div class="titleHead">
                  <h2 class="titleHead-Heading" style="display: flex">
                    <div style="margin-top: 5px">
                      <el-icon>
                        <Key/>
                      </el-icon>
                    </div>
                    更改SSH KEY
                  </h2>
                </div>
                <div style="justify-content: flex-start; display: grid;">
                  <div>
                    <p>
                      更改与该账户关联的SSH密钥。
                    </p>
                  </div>
                  <el-button @click="changeSshVisible = true">更改SSH密钥</el-button>
                  <el-dialog v-model="changeSshVisible" title="更改SSH密钥">
                    <el-form :model="form">
                      <el-form-item label="新SSH密钥" :label-width="formLabelWidth">
                        <el-input v-model="form.userSsh" autocomplete="off"/>
                      </el-form-item>
                    </el-form>
                    <el-button type="primary" @click="changeSsh">
                      确认
                    </el-button>
                  </el-dialog>
                </div>

                <div class="titleHead">
                  <h2 class="titleHead-Heading" style="display: flex">
                    <div style="margin-top: 5px">
                      <el-icon>
                        <Setting/>
                      </el-icon>
                    </div>
                    更改密码
                  </h2>
                </div>
                <div style="justify-content: flex-start; display: grid;">
                  <div>
                    <p>
                      更改该账户的登录密码。
                    </p>
                  </div>
                  <el-button @click="changePasswordVisible = true">更改密码</el-button>
                  <el-dialog v-model="changePasswordVisible" title="更改密码">
                    <el-form :model="form">
                      <el-form-item label="新密码密码" :label-width="formLabelWidth">
                        <el-input v-model="form.userPassword" autocomplete="off"/>
                      </el-form-item>
                      <el-form-item label="确认新密码密码" :label-width="formLabelWidth">
                        <el-input v-model="form.confrimNewPassword" autocomplete="off"/>
                      </el-form-item>
                    </el-form>
                    <el-button type="primary" @click="changePassword">
                      确认
                    </el-button>
                  </el-dialog>
                </div>

                <div class="titleHead">
                  <h2 class="titleHead-Heading" style="display: flex;color: #f85149">
                    <div style="margin-top: 5px">
                      <el-icon>
                        <CloseBold/>
                      </el-icon>
                    </div>
                    删除账户
                  </h2>
                </div>
                <div style="justify-content: flex-start; display: grid;">
                  <div>
                    <p style="color: #f85149">
                      删除操作不可撤销，请三思。
                    </p>
                  </div>
                  <el-popover v-model:visible="deleteVisible" :width="160" placement="top-start">
                    <template #reference>
                      <el-button type="danger">删除账户</el-button>
                    </template>
                    <div>
                      <p>确定删除该账户吗？</p>
                      <div style="text-align: right; margin: 0">
                        <el-button size="small" text @click="deleteVisible = false">
                          否
                        </el-button>
                        <el-button size="small" type="danger" @click="deleteUser">
                          确认
                        </el-button>
                      </div>
                    </div>

                  </el-popover>
                </div>

              </div>
            </el-scrollbar>
          </el-tab-pane>
        </el-tabs>
      </el-main>
      <el-aside width="300px">
        <div style="margin-left: 50px;border-left:1px solid #4c4d4f;height:300px ">
          <div style="margin-top: 50px">
            关于
          </div>
        </div>
      </el-aside>
    </div>
  </div>
</template>

<script>
import '@wangeditor/editor/dist/css/style.css';
import {User, Key, Setting, Search,CloseBold,Message,Bell,Edit,Lock,Unlock} from '@element-plus/icons-vue';
import { onBeforeUnmount, ref, shallowRef, onMounted } from 'vue';
import { Editor, Toolbar} from '@wangeditor/editor-for-vue';
import request from "@/utils/request";
export default {
  name: "UserHomeView",

  setup() {
    // 编辑器实例，必须用 shallowRef，重要！
    const editorRef = shallowRef();


    // 模拟 ajax 异步获取内容
    onMounted(() => {

    });

    // 组件销毁时，也及时销毁编辑器，重要！
    onBeforeUnmount(() => {
      const editor = editorRef.value;
      if (editor == null) return;

      editor.destroy();
    });

    // 编辑器回调函数
    const handleCreated = (editor) => {
      console.log('created', editor);
      editorRef.value = editor; // 记录 editor 实例，重要！
    };

    const printHtml = () => {
      const editor = editorRef.value;
      if (editor == null) return;
      return editor.getHtml();
    };

    const deleteVisible=ref(false)
    const changeUserNameVisible=ref(false)
    const changePasswordVisible=ref(false)
    const changeEmailVisible=ref(false)
    const changeSshVisible=ref(false)
    const activeName = ref("Repo")
    return {
      activeName,
      Search,
      changeSshVisible,
      changeEmailVisible,
      changePasswordVisible,
      changeUserNameVisible,
      deleteVisible,
      editorRef,
      mode: 'default',
      handleCreated,
      printHtml,
    }
  },
  data(){
    return{
      searchMyRepo:'',
      notifyData:[],
      TableData:[],
      form:[],
      userName:'',
      repoName:'',
      dialogVisible:false,
      info:{},
      myHomePage:'',
      userId:'',
      valueHtml:'',
      searchName:'',
    }
  },
  components: {
    User,
    Key,
    Setting,
    CloseBold,
    Message,
    Bell,
    Edit,
    Unlock,
    Lock,
    Editor,
  },
  created(){

    this.userName = this.$route.params.userName
    request.get("/user/id", {
      params: {
        userName: this.userName
      }
    }).then(res => {
      this.userId = res.data
    }).finally(() => (this.loading = false))

    if(this.$route.params.userName!==sessionStorage.getItem("userName")){
      this.myHomePage=false
    }
    else {
      this.myHomePage = true
    }
    setTimeout(()=>{this.load()},500)

  },
  update(){
    this.load()
    window.addEventListener("keydown",this.keyDown)
  },
  destroyed() {
    window.removeEventListener("keydown",this.keyDown,false)
  },

  methods: {

    localSearch(){
      request.get("/repo/list/",{
        params:{
          userId:this.userId,
          repoName:this.searchName,
        }
      }).then(res => {
        console.log(res)
        this.TableData=res.data
      })
    },

    keyDown(e,repoName){
      if(e.keyCode===13||e.keyCode===100){
        this.localSearch(repoName)
      }
    },
    markAll(){
      request.post("/message/read/all", {"userId": this.userId}).then(res => {
        if (res.code === 200) {
          this.$notify({
            title: '成功',
            message: '标记已读成功',
            type: 'success',
          })
          this.load()
        }
      })
    },

    markRead(messageId) {
      request.post("/message/read", {"messageId": messageId}).then(res => {
        if (res.code === 200) {
          this.$notify({
            title: '成功',
            message: '标记已读成功',
            type: 'success',
          })
          this.load()
        }
      })
    },

    confirmDelete(name){
      request.post("/user/login",this.form).then(res => {
        if (res.code === 200) {
          this.$message({
            type: "success",
            message: "账号密码正确"
          })
          request.delete("/delRepo",name).then( res=>{
            if(res.code===200){
              this.$message({
                type:"success",
                message:"删除成功"
              })
              this.load()}
            else{
              this.$message({
                type:"error",
                message:"删除失败"
              })
            }
          })
          this.deleteVisible=false;
        } else {
          this.$message({
            type: "error",
            message: res.msg
          })
          this.deleteVisible=false;
          return;
        }
      })
    },

    handleSizeChange(pageSize){
      this.pageSize= pageSize
      this.load()
    },

    handleCurrentChange(pageNum){
      this.currentPage= pageNum
      this.load()
    },

    load(){
      console.log(this.userId)
      request.get("/repo/list/",{
        params:{
          userId:this.userId
        }
      }).then(res => {
        console.log(res)
        this.TableData=res.data
      })

      request.get("/user/info", {
        params:{
          userIds: this.userId,
        }
      }).then(res => {
        console.log(res)
        this.info=res.data
        this.valueHtml=res.data.description
      })
/*      console.log(this.info.description+"!!!!!!!")
      this.valueHtml=this.info.description*/

      request.get("/messages",{
        params:{
          currentPage: 1,
          pageSize: 10,
          userIds: this.userId,
        }
      }).then(res => {
        this.notifyData=res.data.records
        this.total=res.data.total
      })
    },

    localRepo(){},

    newRepo(){
      this.$router.push("/newRepo");
    },

    validateEmail(email) {
      var re = /\S+@\S+\.\S+/;
      return re.test(email);
    },

    changeUserName() {
      if(this.form.userName==null){
        this.$notify({
          title: '错误',
          message: '用户名不可为空',
          type: 'error',
        })
        this.form.userName=null
        this.changeUserNameVisible=false;
        return;
      }
      if(this.form.userName.length>50){
        this.$notify({
          title: '错误',
          message: '用户名过长',
          type: 'error',
        })
        this.form.userName=null
        this.changeUserNameVisible=false;
        return;
      }
      request.post("/user/renew/name",  {"userId":this.userId,"userName":this.form.userName}).then(res => {
        if (res.code === 200) {
          this.$notify({
            title: '成功',
            message: '修改成功',
            type: 'success',
          })
          sessionStorage.setItem("userName",this.form.userName)
          this.$router.push({
            path:'/'+sessionStorage.getItem("userName")
          })
        }
        else {
          this.$notify({
            title: '错误',
            message: res.msg,
            type: 'error',
          })
        }
      })
      this.form.userName=null;
      this.changeUserNameVisible=false;
    },

    changeUserDescription(){
      if(this.valueHtml==null){
        this.valueHtml="<p>该用户太懒了，还没有自己的个人介绍@_@</p>"
      }
      request.post("/user/renew/des",  {"userId":this.userId,"description":this.valueHtml}).then(res => {
        if (res.code === 200) {
          this.$notify({
            title: '成功',
            message: '修改成功',
            type: 'success',
          })
        }
        else {
          this.$notify({
            title: '错误',
            message: res.msg,
            type: 'error',
          })
        }
      })
    },

    changeEmail() {
      if(this.form.userEmail==null) {
        this.$notify({
          title: '错误',
          message: '邮箱不能为空',
          type: 'error',
        })
        this.form.userEmail=null;
        this.changeEmailVisible=false;
        return
      }
      if(!this.validateEmail('this.form.userEmail')) {
        this.$notify({
          title: '错误',
          message: '邮箱格式错误',
          type: 'error',
        })
        this.form.userEmail=null;
        this.changeEmailVisible=false;
        return
      }
      if(this.form.userEmail.length>60) {
        this.$notify({
          title: '错误',
          message: '邮箱过长',
          type: 'error',
        })
        this.form.userEmail=null;
        this.changeEmailVisible=false;
        return
      }
      request.post("/user/infoChanged",this.form.userEmail,this.userId).then(res => {
        if (res.code === 200) {
          this.$notify({
            title: '成功',
            message: '修改成功',
            type: 'success',
          })
          this.$router.push("/user")
        }
        else {
          this.$notify({
            title: '错误',
            message: res.msg,
            type: 'error',
          })
          this.form.userEmail=null;
          this.changeEmailVisible=false;
        }
      })

    },

    changeSsh() {
      if(this.form.userSsh==null) {
        this.$notify({
          title: '错误',
          message: 'SSH不可为空',
          type: 'error',
        })
        this.form.userSsh=null;
        this.changeSshVisible=false;
        return
      }

      request.post("/user/infoChanged",this.form,{
        params:{
          userID: this.UserId,}
      }).then(res => {
        if (res.code === 200) {
          this.$notify({
            title: '成功',
            message: '修改成功',
            type: 'success',
          })
          this.$router.push("/user")
        }
        else {
          this.$notify({
            title: '错误',
            message: res.msg,
            type: 'error',
          })
          this.form.userSsh=null;
          this.changeSshVisible=false;
        }
      })

    },

    changePassword(){
      if(this.form.userPassword==null) {
        this.$notify({
          title: '错误',
          message: '密码不能为空',
          type: 'error',
        })
        this.form.userPassword=null;
        this.changePasswordVisible=false;
        return
      }

      if(this.form.confrimNewPassword!==this.form.userPassword) {
        this.$notify({
          title: '错误',
          message: '两次密码不一致',
          type: 'error',
        })
        this.form.userPassword=null;
        this.changePasswordVisible=false;
        return
      }

      request.post("/user/renew/password", {
      "userId": this.userId,
      "userPassword": this.form.userPassword
      }).then(res => {
        if (res.code === 200) {
          this.$notify({
            title: '成功',
            message: '修改成功',
            type: 'success',
          })
          this.$router.push("/user")
        }
        else {
          this.$notify({
            title: '错误',
            message: res.msg,
            type: 'error',
          })
        }
      })
      this.form.userPassword=null;
      this.changePasswordVisible=false;
    },

    deleteUser(){
      request.post("/user/delete").then(res => {
        if (res.code === 200) {
          this.$notify({
            title: '删除',
            message: '删除成功',
            type: 'success',
          })
          this.$router.push("/")
        }
        else {
          this.$notify({
            title: '错误',
            message: res.msg,
            type: 'error',
          })
        }
      })
      this.deleteVisible=false;
    },

    delRepo(name){
      let ownerId=this.userId;
      request.post("/repo/delete",{
        "repoName":name,
        "ownerId":ownerId,
      }).then( res=>{
        if(res.code===200){
          this.$message({
            type:"success",
            message:"删除成功"
          })
          this.load()}
        else{
          this.$message({
            type:"error",
            message:"删除失败"
          })
        }
      })
    },

    IntoRepo(repoName){
      sessionStorage.setItem("repoName",repoName)
      this.$router.push({
        path:'/'+this.userName+'/'+repoName+'/tree/master'
      });
    },

  }

}
</script>

<style scoped>
.mainContainer .el-aside {
  position: absolute;
  margin-top: 20px;
}

.scrollbar-item {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 50px;
  margin: 10px;
  text-align: center;
  border-radius: 4px;
  color: #409eff;
}

.titleHead {
  display: grid;
  padding-bottom: 8px;
  margin-bottom: 16px;
  border-bottom: 1px solid #21262d;
  flex-flow: row wrap;
  justify-content: flex-start;
}

.titleHead-Heading {
  font-size: 24px;
  font-weight: 400;
  flex: 1 1 auto;
  order: 0;
}
</style>
